package com.gjb6.customer.common.web;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Message;
import android.support.annotation.Keep;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.cncn.youmengsharelib.ShareListener;
import com.cncn.youmengsharelib.SharePlatform;
import com.cncn.youmengsharelib.ui.SharePlatformsFragment;
import com.gjb6.customer.account.AccountManager;
import com.gjb6.customer.account.Login.ForgetActivity;
import com.gjb6.customer.account.Login.LoginActivity;
import com.gjb6.customer.account.ParamKey;
import com.gjb6.customer.account.UrlCenter;
import com.gjb6.customer.app.MyApplication;
import com.gjb6.customer.app.bean.GetUserInfo;
import com.gjb6.customer.app.bean.MessageList;
import com.gjb6.customer.common.http.MyHttpRequest;
import com.gjb6.customer.common.http.TokenInfo;
import com.gjb6.customer.common.pay.AliPayInfo;
import com.gjb6.customer.common.pay.AlipayHandler;
import com.gjb6.customer.common.pay.PayHelper;
import com.gjb6.customer.common.pay.PayReceiver;
import com.gjb6.customer.common.pay.PayReceiverFail;
import com.gjb6.customer.common.pay.PayResultCallback;
import com.gjb6.customer.common.pay.WechatPayEntity;
import com.gjb6.customer.hxChat.ChatActivity;
import com.gjb6.customer.messageDao.Info;
import com.gjb6.customer.messageDao.InfoDao;
import com.gjb6.customer.messageDao.MessageDao;
import com.gjb6.customer.wxapi.WXPayEntryActivity;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.domain.EaseUser;
import com.pachong.android.framework.citypicker.ChooseCityDialogFragment;
import com.pachong.android.framework.citypicker.Province;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.dialog.AlertDialogFragment;
import com.pachong.android.frameworkbase.utils.AppUtil;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.pachong.android.frameworkbase.utils.NetUtil;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import de.greenrobot.dao.query.QueryBuilder;


/**
 * Created by Zoi.
 * E-mail：KyluZoi@gmail.com
 * 2016/7/28
 * 移动端接口的实现类
 */
public class MobileFunImpl implements MobileImpable {
    private String locationProvider;
    private IWXAPI msgApi;
    private PayTask alipay;
    private PayReceiver payReceiver;
    private PayReceiverFail payReceiverFail;
    private CommonWebviewFragment mFragment;
    private Map<String, EaseUser> contactsMap;

     InfoDao infoDao;
     String allMessage;
    String portrait1;
    String name1;


    private final static  String PORTRAIT ="http://osi16qzy2.bkt.clouddn.com/8ac9da68-ef50-4c5c-8662-83464a485768.png";

    public MobileFunImpl(CommonWebviewFragment fragment) {
        mFragment = fragment;

        initPay();
        getTokenInfo();
    }



    //初始化支付数据
    private void initPay() {
        msgApi = WXAPIFactory.createWXAPI(getContext(), null);
        //将该app注册到微信
        String wetharAppid = WXPayEntryActivity.WETHAR_APPID;
        msgApi.registerApp(wetharAppid);
        alipay = new PayTask(mFragment.getActivity());

        //支付成功的回调
        payReceiver = new PayReceiver(new PayResultCallback() {
            @Override
            public void onSuccess() {
                mFragment.getWebview().loadUrl("javascript:onPaySuccess(0)");
            }

            @Override
            public void onFail() {
                mFragment.getWebview().loadUrl("javascript:onPaySuccess(1)");
            }
        });
        getContext().registerReceiver(payReceiver, new IntentFilter(WXPayEntryActivity.WECHAR_PAY));

        //支付失败的回调
        payReceiverFail = new PayReceiverFail(new PayResultCallback() {
            @Override
            public void onSuccess() {
                mFragment.getWebview().loadUrl("javascript:onPaySuccess(1)");
            }

            @Override
            public void onFail() {
                mFragment.getWebview().loadUrl("javascript:onPaySuccess(0)");
            }
        });
        getContext().registerReceiver(payReceiverFail, new IntentFilter(WXPayEntryActivity.WECHAR_PAY_FAIL));
    }

    //


    //web调支付

    /**
     * 支付 paytype : 0表示支付宝，1表示微信支付
     * @return
     */
    @Keep
    @JavascriptInterface
    @Override
    public void pay(int payType, String orderNum) {

        Log.e("准备支付", "web use pay" + orderNum);
        Log.e("payType", payType + "");
        switch (payType) {
            case 1:
                getAlipayInfo(orderNum);
                break;
            case 0:
//                EasyToast.showToast(mFragment.getContext(),"微信支付暂未开放");
                boolean sIsWXAppInstalledAndSupported = msgApi.isWXAppInstalled()
                        && msgApi.isWXAppSupportAPI(); // 判断微信是否安装
                if (!sIsWXAppInstalledAndSupported) {
                    Toast.makeText(getContext(), "未安装微信", Toast.LENGTH_SHORT).show();
                } else {
                    getWechatPayInfo(orderNum);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 删除系统消息 或者活动消息  0系统。1活动
     * @return
     */
    @Keep
    @JavascriptInterface
    @Override
    public void cleanMessage(int type) {
        MessageDao messageDao = MyApplication.getDaoSession(MyApplication.getAppContext()).getMessageDao();
        QueryBuilder<com.gjb6.customer.messageDao.Message> messageQueryBuilder = messageDao.queryBuilder();
        List<com.gjb6.customer.messageDao.Message> list = messageQueryBuilder.list();
        Log.e("list.toString()",list.toString());
        for (int i=0;i<=list.size();i++){
            if(list.get(i).getType().equals(type+"")){
             messageDao.deleteByKey(list.get(i).getId());
            }
        }
        Collections.reverse(list);
    }

    /**
     * 返回经纬度
     * @return
     */
    @Keep
    @JavascriptInterface
    @Override
    public String getLocation() {
        if(AccountManager.getCurrentAccount().getLongitude()!=null){
            return AccountManager.getCurrentAccount().getLongitude();
        }else{
        return "null";
        }

    }




    /**
     * 发起聊天
     */
    @Keep
    @JavascriptInterface
    @Override
    public void EaseChat(String phone,String customerName,String customerPortrait,String masterName,String masterPortrait){
        if(phone.equals(AccountManager.getCurrentAccount().getPhone())){
            EasyToast.showToast(getContext(),"同一手机号不能聊天");
        }else{
        //点击后将对方名字头像保存下来
        infoDao = MyApplication.getDaoSession(MyApplication.getAppContext()).getInfoDao();
        Info oldInfo = infoDao.queryBuilder().where(InfoDao.Properties.Phone.eq(phone)).unique();
        if(oldInfo!=null) {
            String[] split = phone.split("_");
            String s = split[0];
            MyHttpRequest request = new MyHttpRequest(getContext());
            UrlParams urlParams = new UrlParams();

            urlParams.put("phone", s);
            urlParams.put("type", 2 + "");
            request.get(UrlCenter.GET_USER_INFO, urlParams, new DataRequestListener<GetUserInfo>(GetUserInfo.class) {
                @Override
                public void onStart(Context context, String url) {
                    super.onStart(context, url);
                }
                @Override
                public void onSuccess(GetUserInfo o) {
                    super.onSuccess(o);
                    Long id = oldInfo.getId();
                    infoDao.deleteByKey(id);
                    Info info = new Info(phone, o.getNick_name(), o.getAvatar());
                    infoDao.insert(info);
                    List<Info> list = infoDao.queryBuilder().build().list();
                    Log.e("infoDao1",list.get(0).getPortrait());


                    Intent intent = new Intent(getContext(), ChatActivity.class);
                    intent.putExtra(ParamKey.CUSTOMERNAME,customerName);
                    intent.putExtra(ParamKey.CUSTOMERPORTRAIT,customerPortrait);
                    intent.putExtra(ParamKey.MASTERNAME,o.getNick_name());
                    intent.putExtra(ParamKey.MASTERPORTRAIT,o.getAvatar());
                    intent.putExtra(EaseConstant.EXTRA_USER_ID, phone);
                    intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EMMessage.ChatType.Chat);
                    getContext().startActivity(intent);
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                }
            });

        }else{
                Info info = new Info(phone, masterName, masterPortrait);
                infoDao.insert(info);
                List<Info> list = infoDao.queryBuilder().build().list();
                Log.e("infoDao",list.get(0).getPhone());
                Intent intent = new Intent(getContext(), ChatActivity.class);
                intent.putExtra(ParamKey.CUSTOMERNAME,customerName);
                intent.putExtra(ParamKey.CUSTOMERPORTRAIT,customerPortrait);
                intent.putExtra(ParamKey.MASTERNAME,masterName);
                intent.putExtra(ParamKey.MASTERPORTRAIT,masterPortrait);
                intent.putExtra(EaseConstant.EXTRA_USER_ID, phone);
                intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EMMessage.ChatType.Chat);
                getContext().startActivity(intent);
            }
        }
    }

    /**
     * set contacts map, key is the hyphenate id
     * @param contactsMap
     */
    public void setContactsMap(Map<String, EaseUser> contactsMap){
        this.contactsMap = contactsMap;
    }
    /**
     * 获取会话聊天列表list
     *
     */
    @Keep
    @JavascriptInterface
    @Override
    public String getEaseChatList() {
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        /**
         * lastMsgTime will change if there is new message during sorting
         * so use synchronized to make sure timestamp of last message won't change.
         */
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        InfoDao lastInfoDao = MyApplication.getDaoSession(MyApplication.getAppContext()).getInfoDao();
        ArrayList<MessageList> ml = new ArrayList<>();
        ArrayList<String> isMessage = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            MessageList msg = new MessageList();
            String s1 = list.get(i).getMessageAttachmentPath().toString();
            String[] sp = s1.split("/");
            String phone = sp[sp.length - 1];
            String myPhone = sp[sp.length - 2];
            List<EMMessage> allMessages = list.get(i).getAllMessages();
            String body = list.get(i).getLastMessage().getBody().toString();
            for (int j = 0; j < allMessages.size(); j++) {
                if (allMessages.get(j).getFrom().equals(myPhone) == true) {
                    Log.e("00000", "我发起过消息");
                    isMessage.add("1");
                }
            }
//            if (isMessage.size() == 0) {
                //我从没发起过消息
                         Log.e("我从没发起过消息","我从没发起过消息");
                         InfoDao infoDao1 = MyApplication.getDaoSession(MyApplication.getAppContext()).getInfoDao();
                         Info oldInfo1 = infoDao1.queryBuilder().where(InfoDao.Properties.Phone.eq(phone)).unique();
                        try {
                              oldInfo1.toString();
                                   }catch(NullPointerException npe){
                             AccountManager.getCurrentAccount().setIs_null(true);
                              }
                            if(AccountManager.getCurrentAccount().getIs_null()==true){
                               portrait1 = PORTRAIT;
                                name1 = phone;
                             AccountManager.getCurrentAccount().setIs_null(false);
                        }else{
                                portrait1 = oldInfo1.getPortrait();
                                name1 = oldInfo1.getName();
                                Log.e("portrait1",portrait1);
                                Log.e("portrait1",name1);
                                 }


                        String name = name1;
                        String portrait = portrait1;
                        String[] split = body.split(":");
                        String lastBody = null;
                        Info info = new Info(myPhone, name, portrait);
                        lastInfoDao.insert(info);

                        for (int s = 0; s < split.length; s++) {
                            if (split.length == 2) {
                                lastBody = split[1];
                            } else {
                                for (int z = 0; z < split.length; z++) {
                                    if (split[0].equals("image")) {
                                        lastBody = "\"" + "[图片]" + "\"";
                                    } else if(split[0].equals("voice")){
                                        lastBody = "\""+"[语音]"+"\"";
                                    }else {
                                        lastBody = "\"" + "[表情]" + "\"";
                                    }
                                }
                            }
                        }
                        msg.setBody(lastBody);
                        msg.setPortrait(portrait);
                        msg.setName(name);
                        msg.setPhone(phone);
                        ml.add(msg);
                        allMessage = ml.toString();
            }
// else {
//                //我发起过消息
//                String portrait = lastInfoDao.queryBuilder().where(InfoDao.Properties.Phone.eq(phone)).unique().getPortrait();
//                Log.e("portrait",portrait);
//
//                String name = lastInfoDao.queryBuilder().where(InfoDao.Properties.Phone.eq(phone)).unique().getName();
//                String[] split = body.split(":");
//                String lastBody = null;
//                for (int s = 0; s < split.length; s++) {
//                    if (split.length == 2) {
//                        lastBody = split[1];
//                    } else {
//                        for (int z = 0; z < split.length; z++) {
//                            if (split[0].equals("image")) {
//                                lastBody = "\"" + "[图片]" + "\"";
//                            } else {
//                                lastBody = "\"" + "[表情]" + "\"";
////                            lastBody = body.substring(4, body.length());
//                            }
//                        }
//                    }
//                }
//                msg.setBody(lastBody);
//                Log.e("lastBody",lastBody);
//                msg.setPortrait(portrait);
//                msg.setName(name);
//                msg.setPhone(phone);
//                ml.add(msg);
//
//            }
//            Log.e("allMessageallMessage", "进来了");
//            if (allMessage == null) {
//                Log.e("allMessageallMessage1", ml.toString());}

            return allMessage;
//            mFragment.getWebview().loadUrl("javascript:onMessage(ml.toString())");
//        } else {
//            Log.e("allMessageallMessage", allMessage);
//            mFragment.getWebview().loadUrl("javascript:onMessage(allMessage)");
//            return allMessage;
//        }


    }


    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first.equals(con2.first)) {
                    return 0;
                } else if (con2.first.longValue() > con1.first.longValue()) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }
    /**
     * 获取本地极光推送消息
     */
    @Keep
    @JavascriptInterface
    @Override
    public String message(){
        MessageDao messageDao = MyApplication.getDaoSession(MyApplication.getAppContext()).getMessageDao();
        QueryBuilder<com.gjb6.customer.messageDao.Message> messageQueryBuilder = messageDao.queryBuilder();
        List<com.gjb6.customer.messageDao.Message> list = messageQueryBuilder.list();
        Collections.reverse(list);
        Log.e("list.toString()",list.toString());
;        return list.toString();
    }




    /**
     * 获取微信支付订单详情
     */
    private void getWechatPayInfo(String orderNo) {
        PayHelper.wechatPay(getContext(), orderNo, new DataRequestListener<WechatPayEntity>(WechatPayEntity.class) {

            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }
            @Override
            public void onSuccess(WechatPayEntity o) {
                onStartWechatPay(o);
                super.onSuccess(o);
            }
            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    /**
     * 获取支付宝支付订单详情
     */
    private void getAlipayInfo(String orderNum) {
        PayHelper.aliPay(getContext(), orderNum, new DataRequestListener<AliPayInfo>(AliPayInfo.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }
            @Override
            public void onSuccess(AliPayInfo o) {
                super.onSuccess(o);
                startAliPay(o);
            }
            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });

    }

    private void startAliPay(final AliPayInfo info) {
        Log.e("info",info.getOrderString());
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                // 调用支付接口，获取支付结果
                String result = alipay.pay(info.getOrderString());
                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                alipayHanlder.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 调用阿里支付
     */
    private AlipayHandler alipayHanlder = new AlipayHandler(new PayResultCallback(){

        @Override
        public void onSuccess() {
            mFragment.getWebview().loadUrl("javascript:onPaySuccess(0)");
        }

        @Override
        public void onFail() {
            mFragment.getWebview().loadUrl("javascript:onPaySuccess(1)");
        }
    });//启动阿里支付回调的handle

    @Keep
    @JavascriptInterface
    @Override
    public String getTokenInfo() {
        String token = null;
        if (AccountManager.isTokenValid()) {
            TokenInfo tokenInfo = AccountManager.getTokenInfo();
            token = tokenInfo.toString();
//            token = GsonUtils.toJson(tokenInfo);
        }
        return token;
    }

    @Keep
    @JavascriptInterface
    @Override
    public void  showRegionActionssheet(String info){
        ChooseCityDialogFragment chooseCityDialog = new ChooseCityDialogFragment();
        chooseCityDialog.show(mFragment.getChildFragmentManager());
        chooseCityDialog.setOnCitySelectedListener(new ChooseCityDialogFragment.OnCitySelectedListener() {
            @Override
            public void onSelected(Province province, Province.City city, Province.Country country) {
                String s = "{"+ "\"province\":"+"{"+"\"code\":"+"\""+province.code+'\"'+","+"\"label\":"+"\""+province.label+'\"'+"}"+
                              ", \"city\":"+"{"+"\"code\":"+"\""+city.code+'\"'+","+"\"label\":"+"\""+city.label+'\"'+"}"+
                        ", \"district\":" +"{"+ "\"code\":"+"\""+country.code+'\"'+","+"\"label\":"+"\""+country.label+'\"'+"}"+
                        '}';
//                Log.e("sssssss", s);
//                EventBus.getDefault().post(s);
                mFragment.callLoadUrl(s);
//                mFragment.getWebview().callJsFunction("onUploadSuccess", s);

            }
        });


    }
    @Keep
    @JavascriptInterface
    @Override
    public void tocleanCache(){
        //清除缓存
        final File cacheDir =mFragment.getActivity().getCacheDir();
        final String cacheSize = FileUtils.size(cacheDir);
        //弹出Dialog
        showCacheDialog(cacheDir, cacheSize);
        Toast.makeText(getContext(), cacheSize, Toast.LENGTH_SHORT).show();
        FileUtils.delFilesFromPath(cacheDir);

//
    }

    private void showCacheDialog(File cacheDir, String cacheSize) {

        if ("0B".equals(cacheSize)) {
            final AlertDialogFragment nullCacheDialogFrag = new AlertDialogFragment();
            nullCacheDialogFrag.setMessage("无缓存")
                    .setPositiveButton("确认", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            nullCacheDialogFrag.dismiss();
                        }
                    }).show(mFragment.getFragmentManager());
        }else{
            final AlertDialogFragment cleanDialogFrag = new AlertDialogFragment();
            cleanDialogFrag.setMessage("确认清除" + cacheSize + "缓存?")
                    .setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            cleanDialogFrag.dismiss();
                        }
                    })
                    .setPositiveButton("确定", new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            FileUtils.delFilesFromPath(cacheDir);
                            cleanDialogFrag.dismiss();
                            Toast.makeText(getContext(), "已清除" + cacheSize + "缓存!", Toast.LENGTH_SHORT).show();
                        }
                    })
                    .show(mFragment.getFragmentManager());
        }
    }

    //调用微信支付
    private void onStartWechatPay(WechatPayEntity wechatPayEntity) {
        PayReq request = new PayReq();
        //微信分配的公众账号ID
        request.appId = wechatPayEntity.getAppid();
        //微信支付分配的商户号
        request.partnerId = wechatPayEntity.getPartnerid();
        //微信返回的支付交易会话ID
        request.prepayId = wechatPayEntity.getPrepayid();
        //暂填写固定值Sign=WXPay
        request.packageValue = wechatPayEntity.getPackageX();
        //随机字符串，不长于32位。推荐随机数生成算法
        request.nonceStr = wechatPayEntity.getNoncestr();
        //时间戳，请见接口规则-参数规定
        request.timeStamp = wechatPayEntity.getTimestamp();
        //签名，详见签名生成算法
        request.sign = wechatPayEntity.getSign();
        msgApi.sendReq(request);
    }

    @Keep
    @JavascriptInterface
    @Override
    public void login() {
        Log.d("kyluzoi", "web use login");
    }

    @Keep
    @JavascriptInterface
    @Override
    public void uploadImage(String tag) {
        /*PhotoAlertFragment photoAlertFragment = new PhotoAlertFragment();
        photoAlertFragment.show(getActivity().getFragmentManager(), "tag");
        photoAlertFragment.setOnCitySelectedListener(this);
        mSynTag = tag;*/
    }

    @Keep
    @JavascriptInterface
    @Override
    public void showToast(String url) {
//        return mConnectable.callback();
    }

    @Keep
    @JavascriptInterface
    @Override
    public void share(String title, String content, String imgUrl, String targetUrl) {
        SharePlatformsFragment fragment = SharePlatformsFragment.newInstance(title, content, imgUrl, targetUrl);
        fragment.setShareListener(new ShareListener() {
            @Override
            public void onShareSuccess(Activity shareActivity, SharePlatform platform) {
                Toast.makeText(getContext(), "分享成功", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onShareFailed(Activity shareActivity, SharePlatform platform) {
                Toast.makeText(getContext(), "分享失败", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onShareCancel(Activity shareActivity, SharePlatform platform) {
                Toast.makeText(getContext(), "取消分享", Toast.LENGTH_SHORT).show();
            }
        });
        fragment.show(mFragment.getFragmentManager(), "");
    }

    @Keep
    @JavascriptInterface
    @Override
    public void back() {
        mFragment.getActivity().finish();
    }

    @Keep
    @JavascriptInterface
    @Override
    public void showTabBar() {
    }

    @Keep
    @JavascriptInterface
    @Override
    public void hideTabBar() {
    }

    @Keep
    @JavascriptInterface
    @Override
    public boolean netIsAvalible() {
        return NetUtil.isAvalible(mFragment.getActivity());
    }

    @Keep
    @JavascriptInterface
    @Override
    public int getVersionCode() {
        return AppUtil.getVersionCode(mFragment.getActivity());
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }
    //上下文
    private Context getContext() {
        return mFragment.getContext();
    }

    //退出登录
    @Keep
    @JavascriptInterface
    @Override
    public void logOut() {
        //弹出Dialog
        showCacheDialog();
//        getMessageDao().deleteAll();
    }

    public static MessageDao getMessageDao() {
        return MyApplication.getDaoSession(MyApplication.getAppContext()).getMessageDao();
    }

    //忘记密码
    @Keep
    @JavascriptInterface
    @Override
    public void forgetWord() {
        //弹出Dialog
        ForgetActivity.start(mFragment.getContext(),2);
    }

    private void showCacheDialog() {
        final AlertDialogFragment dialogOutFragment = new AlertDialogFragment();
        dialogOutFragment.setMessage("是否确定退出？").setNegativeButton("取消",
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialogOutFragment.dismiss();
                    }
                })
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AccountManager.getTokenInfo().clear();
                        dialogOutFragment.dismiss();
                        //避免返回到退出的界面
                        mFragment.getActivity().finish();
                        //环信退出登录
                        EMClient.getInstance().logout(true);
                        LoginActivity.start(mFragment.getContext());
                    }
                })
                .show(mFragment.getFragmentManager());
    }
}
